import * as React from 'react';
import { createElement, forwardRef } from 'react';
import { App, Col, ConfigProvider, Form, Row } from 'antd';
import { legacyLogicalPropertiesTransformer, StyleProvider } from '@ant-design/cssinjs';
import { generatorClass, groupArray, isMobile } from '../utils';
import classNames from 'classnames';
import './formContainer.less';
import { FormContainerProvider, useFormContainerSelector } from './processor';
import { FormContainerWrapper as MobileFormContainerWrapper } from '../../components-mobile/form-container';
import { project } from '@alilc/lowcode-engine';

import zhCN from 'antd/locale/zh_CN';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';

dayjs.locale('zh-cn');

export interface FormContainerProps {
  max: string;
}
/**
 * Form容器包装器。lowcode-engine不支持直接使用hooks组件，需要包裹一层，要不内容元素没办法直接嵌入
 */
export const FormContainerWrapper = forwardRef<FormContainerProps>(
  ({ cols, children, id, onFinish, gutterX, gutterY, __designMode }: any, ref) => {
    // const [disabled, setDisabled] = useState<boolean>(false);
    const [form] = Form.useForm();

    // window.cc = form;
    const [changeReadonly] = useFormContainerSelector((s) => [s.changeReadonly]);

    React.useImperativeHandle(
      ref,
      () => {
        return {
          formRef: form,
          changeReadonly,
        };
      },
      [],
    );

    const selectAndClearToFix = () => {
      const nodeId = Array.from(project.documents[0].nodesMap.keys());
      // for (let i = 0; i < nodeId.length; i++) {
      //   await project.documents[0].selection.select(nodeId[i]);
      // }
      project.documents[0].selection.select(nodeId[nodeId.length - 3]);
      project.documents[0].selection.clear();
    };
    React.useEffect(() => {
      setTimeout(() => {
        selectAndClearToFix();
      }, 0);
    }, []);
    const getChildren = () => {
      // return children;
      // if (React.Children.count(children) <= 1) {
      //   return children;
      // }
      if (children && children.length === 0) {
        return [];
      }
      return children;
      const newArray = groupArray(React.Children.toArray(children), cols);
      // 根据item的cols进行分组,每满24生成一个新的Row
      // let rowGroup = groupArrayByCol(React.Children.toArray(children));
      let rowGroup = React.Children.toArray(children);
      return (
        <Row
          gutter={[gutterX, gutterY]}
          wrap={true}
          className={generatorClass('form-container-row')}
        >
          {rowGroup.map((item, index) => {
            const { props } = item;
            const name = props?.componentId || props?.__id;
            const componentName = props?._componentName || props.componentName;
            // 占整行内容
            if (['FieldLayout'].includes(componentName)) {
              return (
                <Col key={name} span={24}>
                  {item}
                </Col>
              );
            }
            return (
              <Col key={name} span={props?.cols || 24}>
                {name && item}
              </Col>
            );
          })}
        </Row>
      );
    };
    const rootClassNames = classNames(generatorClass('form-container'));
    // 表单默认值
    const getFormDefaultValue = () => {
      const defaultValue = {};
      if (children && children.length > 0) {
        children.forEach((item) => {
          if (
            item.props.columnConfig &&
            item.props.columnConfig.defaultValue !== undefined &&
            item.props.columnConfig.defaultValue !== null
          ) {
            defaultValue[item.props.componentId || item.props.__id || item.key] =
              item.props.columnConfig.defaultValue;
          }
        });
      }
      return defaultValue;
    };
    // 重新设置表单值，否则在修改默认值时，画布的默认值不会更新
    if (__designMode === 'design') {
      // 只有编辑态设置
      form.setFieldsValue(getFormDefaultValue());
    }
    return (
      <Form
        style={{
          width: '100%',
          display: 'flex',
          flexWrap: 'wrap',
          gap: `${gutterY}px ${gutterX}px`,
        }}
        form={form}
        initialValues={getFormDefaultValue()}
        className={rootClassNames}
        id={id}
        onFinish={onFinish}
      >
        {getChildren().length === 0 ? (
          <div className="placeholder">
            <img src="/lowcode/fields/placeholder.webp" alt="" />
            <span>拖拽或点击左侧字段创建表单</span>
          </div>
        ) : (
          getChildren()
        )}
      </Form>
    );
  },
);

/**
 * 容器组件
 */
export class FormContainerClass extends React.PureComponent<FormContainerProps> {
  render() {
    // 向下传递ref
    const { forwardedRef, ...otherProps } = this.props;
    const mobile = isMobile();
    return (
      <ConfigProvider locale={zhCN}>
        <StyleProvider hashPriority="high" transformers={[legacyLogicalPropertiesTransformer]}>
          {/* <App style={{ height: '100%' }}> */}
          <FormContainerProvider isMobile={mobile}>
            {mobile ? (
              <MobileFormContainerWrapper {...otherProps} ref={forwardedRef} />
            ) : (
              <FormContainerWrapper {...otherProps} ref={forwardedRef} />
            )}
          </FormContainerProvider>
          {/* </App> */}
        </StyleProvider>
      </ConfigProvider>
    );
  }
}

/**
 * 简单包装，不做任何处理
 * 部分组件ref比较特殊，包一层会解决这个问题
 */
export function withWrap(Comp: any) {
  return forwardRef((props: any, ref: any) => {
    // console.log('q=>00000000', window.AliLowCodeEngine, props,);
    // design态的时候后render泰分别对ref做特殊处理
    const isDesign = props.__designMode === 'design';
    if (isDesign) {
      return <Comp {...props} ref={ref} forwardedRef={ref} />;
    }
    return <Comp {...props} forwardedRef={ref} />;
  });
}

export const FormContainer = withWrap(FormContainerClass);
